class Scheduler {
  constructor(tasks, max) {
    this.tasks = tasks || [];
    this.max = max;
  }

  taskCount = 0;

  add(task) {
    this.tasks.push(task);
  }

  taskStart() {
    for (let i = 0; i < this.max; i++) {
      this.run();
    }
  }

  run() {
    if (this.taskCount < this.max && this.tasks.length > 0) {
      this.tasks
        .shift()()
        .then(() => {
            this.run()
        });
    }
  }
}

var scheduler = new Scheduler([], 2);

function timeout(time) {
  return new Promise((resolve) => {
    setTimeout(resolve, time);
  });
}

function addTask(time, order) {
  scheduler.add(() => timeout(time).then(() => console.log(order)));
}

addTask(1000, 1);
addTask(1000, 2);
addTask(1000, 3);
addTask(1000, 4);

scheduler.taskStart();
